/**
 * Created with  SublimeText
 * @Author:      Lyle
 * @DateTime:    2016-11-10 13:46:17
 * @Description: myProfile
 */

define(function(require, exports, module) {

    var id = 'myProfile',
        tabIndex = 0,
        myProfileTpl = require('{base}/tpls/myProfile.tpl'),
        myProfileProfileJs = require('{base}/components/myProfileProfile.js'),
        myProfilePhotoJs = require('{base}/components/myProfilePhoto.js'),
        myProfileAboutMeJs = require('{base}/components/myProfileAboutMe.js'),
        myProfileActivitiesJs = require('{base}/components/myProfileActivities.js'),
        myProfileCommentsJs = require('{base}/components/myProfileComments.js'),
        myProfileTplJs = require('{base}/pages/myProfileTpl.js'),
        switchTabJs = require('{base}/tools/plugs/switchTab.js');

    var switchTabUserInfo = new switchTabJs({
        containerId: 'myProfile',
        menuTabClass: 'menuTabClass',
        menuTabActionClass: 'active',
        contentTabClass: 'contentTabClass',
        callback: function(index) {
            tabIndex = index;
            myProfile.tabRender(tabIndex);
            if (tabIndex > 0) {
                $('#' + id).find('.myProfileEditInfoNav').hide();
            } else {
                $('#' + id).find('.myProfileEditInfoNav').show();
            }
        },
    });

    var myProfile = _.extend(myProfileTplJs, {

        templateMyProfile: _.template(myProfileTpl),

        id: id,

        render: function(obj) {
            $('#' + id).find('.bodyRight').html(this.templateMyProfile(this.getUserData()));
            this.bindEvt();
            this.basicInfoInt(this.getUserData());
            if (obj.type == 'tab' && obj.param) {
                tabIndex = parseInt(obj.param);
            }
            switchTabUserInfo.gotoTabs(tabIndex);
        },

        bindEvt: function() {
            var tthis = this,
                dom = $('#' + id);
            switchTabUserInfo.bindEvt();


            dom.find('.basicInfo').find('.age').find('.edit').on('click', function() {
                switchTabUserInfo.gotoTabs(0);
                $('#' + id).find('div[keyName="age"]')[0].scrollIntoView();
            });

            dom.find('.basicInfo').on('click', '.baseKey .edit', function() {
                var keyName = $(this).parents('.baseKey').attr('keyname');
                tthis.switchKeyEdit(keyName);
            });

            dom.find('.basicInfo').on('click', '.baseKey .btnSave', function() {
                if ($(this).hasClass('btnDisabled')) {
                    return false;
                }
                var keyName = $(this).parents('.baseKey').attr('keyname');
                tthis.ajaxPostUserInfo(keyName);
            });

            dom.find('.basicInfo').on('click', '.baseKey .btnCancel', function() {
                var keyName = $(this).parents('.baseKey').attr('keyname');
                tthis.switchKeyRead(keyName);
            });

            dom.find('.basicInfo').on('input', '.baseKey *[listenInput=true]', function() {
                var lengthDom = $(this).parent().find('.annotation').find('.length');
                if (lengthDom.length > 0) {
                    var maxlength = $(this).attr('maxlength'),
                        minlength = $(this).attr('minlength'),
                        btnSave = $(this).closest('.baseEdit').find('.btnSave'),
                        nums = parseInt(maxlength) - $(this).val().length;
                    lengthDom.html(nums > 0 ? nums : 0);
                    if (typeof(minlength) != 'undefined' && $(this).val().length < minlength) {
                        btnSave.addClass('btnDisabled');
                    } else {
                        btnSave.removeClass('btnDisabled');
                    }
                }
            });
        },

        getUserData: function() {
            var obj = {
                userInfo: JSON.parse(Util.getSessionStorage('userInfo')),
                userStatus: JSON.parse(Util.getSessionStorage('userStatus'))
            }
            return obj;
        },

        ajaxPostUserInfo: function(keyName) {
            var tthis = this,
                postUserInfo = tthis[keyName + 'GetVal']();
            var callback = function(data) {
                if (data.results) {
                    tthis[keyName + 'SetVal'](data.data);
                    this.switchKeyRead(keyName);
                }
            };
            Share.updateProfile(postUserInfo, callback.bind(this));
        },

        tabRender: function(index) {
            var contentTab = $('#' + id).find('.contentTabClass').eq(index),
                tabName = contentTab.attr('tabName');
            //console.log('tabRender', index, tplName);
            if ($.trim(contentTab.html()) == '') {
                if (Util.firstCapitalize(tabName) == 'MyProfileProfile') {
                    contentTab.html(myProfileProfileJs.render(this));
                    myProfileProfileJs.componentMount();
                } else if (Util.firstCapitalize(tabName) == 'MyProfilePhoto') {
                    contentTab.html(myProfilePhotoJs.render(this));
                    myProfilePhotoJs.componentMount();
                } else if (Util.firstCapitalize(tabName) == 'MyProfileAboutMe') {
                    contentTab.html(myProfileAboutMeJs.render(this));
                    myProfileAboutMeJs.componentMount();
                } else if (Util.firstCapitalize(tabName) == 'MyProfileActivities') {
                    contentTab.html(myProfileActivitiesJs.render(this));
                    myProfileActivitiesJs.componentMount();
                } else if (Util.firstCapitalize(tabName) == 'MyProfileComments') {
                    contentTab.html(myProfileCommentsJs.render(this));
                    myProfileCommentsJs.componentMount();
                }
            }
        },

        basicInfoInt: function(data) {
            if (typeof(data.userInfo) != 'undefined' && data.userInfo != null) {
                var obj = {
                    username: data.userInfo.account.username,
                    expired: data.userInfo.account.show_expiration,
                    age: data.userInfo.account.age,
                    city: data.userInfo.account.city,
                    state: data.userInfo.account.state_name,
                    country: data.userInfo.account.country_name,
                }
                var dom = $('#' + id);
                dom.find('.myProfileUsername').html(obj.username);
                if (parseInt(obj.expired) == 1) {
                    dom.find('.myProfileExpired').html(Share.repalceTpl(Lang.myProfileExpired, ['<span class="myProfileUpgrade">Upgrade</span>']));
                }
                dom.find('.myProfileAge').html(obj.age);
                var location = '';
                if ($.trim(obj.city).length > 0) {
                    $.trim(location.length) == 0 ? location += obj.city : location += ', ' + obj.city;
                }
                if ($.trim(obj.state).length > 0) {
                    $.trim(location.length) == 0 ? location += obj.state : location += ', ' + obj.state;
                }
                if ($.trim(obj.country).length > 0) {
                    $.trim(location.length) == 0 ? location += obj.country : location += ', ' + obj.country;
                }
                dom.find('.myProfileLocation').html(location);

                this.switchKeyRead('status');
            }
        },

        setBaseAge: function() {
            var userInfo = JSON.parse(Util.getSessionStorage('userInfo')),
                age = userInfo.account.age;
            //myProfileAge
            $('#' + id).find('.basicInfo').find('.myProfileAge').html(age);
        },

        switchKeyRead: function(name) {
            var html = this.createDom(name, 'Read'),
                Dom = $('#' + id).find('.basicInfo'),
                readDom = Dom.find('*[keyName=\'' + name + '\']').find('.baseRead'),
                editDom = Dom.find('*[keyName=\'' + name + '\']').find('.baseEdit');
            readDom.html(html);
            readDom.show();
            editDom.hide();
        },

        switchKeyEdit: function(name) {
            var html = this.createDom(name, 'Edit'),
                Dom = $('#' + id).find('.basicInfo'),
                readDom = Dom.find('*[keyName=\'' + name + '\']').find('.baseRead'),
                editDom = Dom.find('*[keyName=\'' + name + '\']').find('.baseEdit');
            editDom.html(html);
            editDom.show();
            readDom.hide();
        },

        createDom: function(name, type) {
            if (this[name + type]) {
                return this[name + type]();
            } else {
                console.log(name + type + 'function not fonund!');
            }
        },

        statusRead: function() {
            var userData = this.getUserData();
            if (typeof(userData) != 'undefined' && userData != null) {
                var status = userData.userInfo.about.headline,
                    html = "<div> Status:  <span class='edit'></span> <span class='myProfileStatus'>" + status + "</span> </div>";
                return html;
            }
        },

        statusEdit: function() {
            var userData = this.getUserData();
            if (typeof(userData) != 'undefined' && userData != null) {
                var status = userData.userInfo.about.headline,
                    html = '<div>' +
                    '<h3>Status: <span class="edit"></span></h3>' +
                    '<textarea listenInput=true minlength="10" maxlength="140" rows="3" cols="20" placeholder="What\'s on your mind?">' + status + '</textarea>' +
                    '<div class="annotation"><strong class="length">' + (140 - status.length) + '</strong> characters remaining</div>' +
                    '<div class="submitBox">' +
                    '<div class="btnCancel">Cancel</div>' +
                    '<div class="btn btnSave">Save</div>' +
                    '</div>' +
                    '</div>';
                return html;
            }
        },

        statusGetVal: function() {
            var userInfo = {
                'title': $('#' + id).find('*[keyName=\'status\']').find('.baseEdit').find('textarea').val()
            };
            return userInfo;
        },

        statusSetVal: function(data) {
            var userInfo = JSON.parse(Util.getSessionStorage('userInfo'));
            userInfo.about.headline = data.title;
            Util.setSessionStorage('userInfo', JSON.stringify(userInfo));
        },

        myProfilePhotoComponentChange: function(typeString) {
            var userInfo = Share.getUserInfo();
            if (typeString == 'photoNum') {
                var num = userInfo.pictures.length + userInfo.private_pictures.length;
                $('#' + this.id).find('.profileInfo').find('.photoNum').html('(' + num + ')');
            } else if (typeString == 'mainPhoto') {

            }
        },

        myProfileProfileComponentChange: function(typeString) {
            var tthis = this;
            if (typeof(typeString) != 'undefined' && typeString == 'age') {
                tthis.setBaseAge();
            }
        },

        myProfileEditInfoNavComponentChange: function(typeString, val) {
            var tthis = this;
            if (typeof(typeString) != 'undefined' && typeString == 'anchor') {
                $('#' + id).find('div[anchor="' + val + '"]')[0].scrollIntoView();
            }
        },

    })

    module.exports = myProfile;
});
